<?php

require '../SparrowEvent.php';

SparrowEvent::start();
define('APP_DEBUG', true);

// 自动加载
spl_autoload_register(function ($clazz) {
        require '../' . str_replace('\\', '/', $clazz) . '.php';
});

// 注册异常和错误
set_exception_handler(function (\Throwable $exception) {
    // 处理异常
    if ($exception instanceof \Exception) {
        echo json_encode([
            'code' => $exception->getCode(),
            'message' => $exception->getMessage(),
        ]);
    }
    // 处理错误
    if ($exception instanceof \Error && APP_DEBUG) {
        echo '<h1> 发生了错误 </h1>';
        echo 'Message:' . $exception->getMessage() . '<br />';
        echo 'File:' . $exception->getFile() . '<br />';
        echo 'Line:' . $exception->getLine() . '<br />';
        echo '=====================================' . '<br />';
        $trace = $exception->getTraceAsString();
        $traceArr = explode('#', $trace);
        foreach ($traceArr as $value) {
            echo $value . '<br />';
        }
    }
});

// 加载配置
\vendor\Config::load(include '../Configs/App.php');

// 分解路由
$uri = substr($_GET['s'], 1);
// 判断是否为自定义路由
if(\vendor\Config::get('CUSTOM_ROUTE')){
    $routeMap = include '../Configs/Route.php';
    if(!isset($routeMap[$uri])){
        throw new \Exception('Route not found!');
    }
    $route = $routeMap[$uri];
} else {
    // 默认路由[模块，控制器，方法]
    $route = explode('/', $uri);
    if(count($route) < 3){
        throw new \Exception('Route not found!');
    }
}
if($route instanceof \Closure){
    echo call_user_func($route);
    die();
}
list($module, $controller, $action) = $route;
// 禁止访问的模块
if(in_array($module, \vendor\Config::get('DENY_ACCESS_MODULE'))){
    throw new \Exception('Route not found!');
}
SparrowEvent::routeDispatchFirst($uri);

// 检测相关目录是否具有权限
if(!is_writable('/var/log/app')){
    throw new Exception('Log dir not writable!');
}

// 执行应用
$clazz = '\\App\\' . $module . '\\' . 'Controller\\' . $controller;
$response = (new $clazz)->$action();
SparrowEvent::shutdown($response);

echo $response;